import React from 'react';
import { Button, Layout, message, Modal, Steps, Table, Row, Col, Input, Image } from 'antd';
import { useState, useEffect, useRef } from 'react';
import { Content, Header } from 'antd/lib/layout/layout';
import InstrumentCard from '../InstrumentCard';
import axios from 'axios';
import Config from '../../Config';
import * as moment from 'moment';
import { useSelector } from 'react-redux';
import { selectUser } from '../../redux/Slice/userSlice';
const ItemList = props => {
  const [examineData, SetExamData] = useState([]);
  const [tableLoading, SetTableLoading] = useState(true);
  const [InfoModal, SetInfoMoadl] = useState(false);
  const childRef = useRef();
  const [curInfo, SetCurInfo] = useState({
    id: null,
    YQBH: -1,
    YQMC: '',
    type: null,
    taskId: '',
    taskName: '',
    username: '',
    time: '',
    state: null,
    errReason: '',
  });
  const [refresh, SetRefresh] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [ImgModal, SetImgModal] = useState(false);
  const [ImgId, SetImgId] = useState('');
  let username = useSelector(selectUser);
  const Action = props => {
    if (props.type == 1) {
      return (
        <>
          <Button
            onClick={() => {
              console.log(props.value);
              SetCurInfo(props.value);
              SetInfoMoadl(true);
              childRef.current.SetReFresh(!childRef.current.refresh);
            }}
            type="primary"
            size="large"
          >
            {props.value.taskName == '仪器修改' ? '修改' : '详情'}
          </Button>
        </>
      );
    } else if (props.type == 2) {
      return (
        <>
          {props.value.state == -1 ? (
            <></>
          ) : (
            <>
              <Button
                onClick={() => {
                  console.log(props.value);
                  SetCurInfo(props.value);
                  SetInfoMoadl(true);
                  childRef.current.SetReFresh(!childRef.current.refresh);
                }}
                type="primary"
                size="large"
              >
                详情
              </Button>
            </>
          )}
        </>
      );
    } else if (props.type == 3) return <></>;
    else return <></>;
  };
  const columns = [
    {
      title: '申请编号',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '仪器名称',
      dataIndex: 'YQMC',
      key: 'YQMC',
    },
    {
      title: '操作类型',
      dataIndex: 'type',
      key: 'type',
      //   filters: [
      //     { text: '录入', value: 1 },
      //     { text: '修改', value: 2 },
      //     { text: '删除', value: 3 },
      //   ],
      //   onFilter: (value, record) => record.type === value,
      render: (_, record) => {
        if (record.type == 1) {
          return <span>录入</span>;
        } else if (record.type == 2) {
          return <span>修改</span>;
        } else if (record.type == 3) {
          return <span>删除</span>;
        }
      },
    },
    {
      title: '申请人',
      dataIndex: 'username',
      key: 'username',
    },
    {
      title: '申请时间',
      dataIndex: 'time',
      key: 'time',
    },
    {
      title: '当前状态',
      dataIndex: 'taskName',
      key: 'taskName',
      render: (_, value) => {
        if (value.taskName == '完成') {
          return <span style={{ color: '#00AF9B' }}>操作成功</span>;
        } else if (value.taskName == '仪器修改' || value.taskName == '失败') {
          return <span style={{ color: '#FF2D55' }}>失败</span>;
        }
        return <span style={{ color: '#FFB800' }}>{value.taskName}</span>;
      },
    },
    {
      title: '操作',
      key: 'action',

      render: (_, value) => {
        console.log(value);
        return (
          <>
            <Action type={props.type} value={value}></Action>
            {value.processId != '-1' ? (
              <Button
                type="primary"
                size="large"
                style={{ marginLeft: '15px' }}
                onClick={() => {
                  SetImgId(Config.realUrl + 'activiti/' + value.processId);
                  SetImgModal(true);
                }}
              >
                查看流程图
              </Button>
            ) : (
              <></>
            )}
          </>
        );
      },
    },
  ];

  useEffect(() => {
    SetTableLoading(true);
    axios
      .get(Config.baseURL + '/instrument/myexamine')
      .then(res => {
        if (res.data.code == 1) {
          console.log(res.data.data);
          let data = res.data.data;
          let dataSource = [];
          for (let i = 0; i < data.examine.length; i++) {
            if (data.examine[i].type == props.type)
              dataSource.push({
                ...data.examine[i],
                taskName: data.taskName[i],
                taskId: data.taskId[i],
                processId: data.processId[i],
              });
          }
          SetExamData(dataSource);
          SetTableLoading(false);
        } else if (res.data.code >= 10000) {
          message.error(res.data.message, 2);
        }
      })
      .catch(err => {
        message.error('服务器出错，请联系管理员', 2);
        console.log(err);
      });
  }, [refresh]);
  const Edit = () => {
    const getval = async () => {
      setIsLoading(true);
      let val = await childRef.current.editFormValue();
      console.log(val);
      axios
        .post(Config.baseURL + '/instrument/registerEdit', {
          ...val,
          edit: 1,
          examId: curInfo.id,
          YQBH: curInfo.YQBH,
          taskId: curInfo.taskId,
        })
        .then(res => {
          if (res.data.code == 1) {
            message.success('申请修改成功', 2, () => {
              setIsLoading(false);
            });
          } else if (res.data.code >= 10000) {
            console.log(res.data.data);
            message.error('申请修改失败，原因：' + res.data.message, 2, () => {
              setIsLoading(false);
            });
          }
        })
        .catch(err => {
          message.error('申请修改失败，原因：' + err, 2, () => {
            setIsLoading(false);
          });
        });
    };
    getval();
  };
  const GiveUp = () => {
    // setIsLoading(true);
    // axios
    //   .post(Config.baseURL + '/instrument/InstrumentExamine', {
    //     username: username,
    //     id: curInfo.id,
    //     pass: 0,
    //     taskId: curInfo.taskId,
    //     time: moment().format('YYYY-MM-DD HH:mm:ss'),
    //   })
    //   .then(res => {
    //     if (res.data.code == 1) {
    //       message.success('成功', 2, () => {
    //         setIsLoading(false);
    //         SetInfoMoadl(false);
    //         SetRefresh(!refresh);
    //       });
    //     } else if (res.data.code >= 10000) {
    //       message.error('失败 ' + res.data.message, 2);
    //       setIsLoading(false);
    //     }
    //   })
    //   .catch(err => {
    //     message.error('后台出错 ' + err, 2);
    //     setIsLoading(false);
    //   });
  };
  const BottomView = () => {
    return (
      <>
        <Row style={{ marginTop: '20px' }}>
          <Col style={{ textAlign: 'center' }} span={8}>
            <h3 style={{ display: 'inline', fontWeight: 'bold' }}>申请人：</h3>
            {curInfo.username}
          </Col>
          <Col style={{ textAlign: 'center' }} span={8}>
            <h3 style={{ display: 'inline', fontWeight: 'bold' }}>申请时间：</h3>
            {curInfo.time}
          </Col>
        </Row>
        {curInfo.taskName == '仪器修改' ? (
          <Row style={{ marginTop: '20px', height: '25px' }}>
            <Col span={12}>
              <h3>不通过原因：{curInfo.errReason}</h3>
            </Col>
            <Col span={8}></Col>
            <Col style={{ textAlign: 'center' }} span={4}>
              <Button
                style={{ marginRight: '15px' }}
                danger
                type="primary"
                size="large"
                loading={isLoading}
                onClick={GiveUp}
              >
                放弃
              </Button>
              <Button onClick={Edit} loading={isLoading} type="primary" size="large">
                提交修改
              </Button>
            </Col>
          </Row>
        ) : (
          <></>
        )}
      </>
    );
  };
  return (
    <>
      <Layout>
        <Header
          style={{
            borderRadius: '5px 5px 0px 0px',
            height: '40px',
            padding: '0px 15px',
            margin: '0px 0px',
            backgroundColor: 'white',
            textAlign: 'left',
            lineHeight: '40px',
          }}
        >
          <h3>仪器审核</h3>
        </Header>
        <Content style={{ padding: '10px 20px', backgroundColor: 'white' }}>
          <Table
            style={{ border: '2px solid #E6F7FF', borderRadius: '2px' }}
            loading={tableLoading}
            columns={columns}
            dataSource={examineData}
          ></Table>
        </Content>
      </Layout>
      <Modal
        title="仪器审核"
        visible={InfoModal}
        onCancel={() => {
          SetInfoMoadl(false);
        }}
        footer={null}
        width={1653}
        style={{ top: 20 }}
      >
        <Row
          style={{
            borderBottom: '3px solid #1890FF',
            height: '500px',
            overflow: 'auto',
            overflowX: 'hidden',
          }}
        >
          <Col span={24}>
            <InstrumentCard
              disable={curInfo.taskName != '仪器修改'}
              curInfo={curInfo}
              SetCurInfo={SetCurInfo}
              ref={childRef}
            ></InstrumentCard>
          </Col>
        </Row>
        {BottomView()}
      </Modal>
      <Modal
        title="流程图"
        visible={ImgModal}
        onCancel={() => {
          SetImgModal(false);
        }}
        footer={null}
        width={1500}
        style={{ top: 20 }}
      >
        <Row>
          <Col span={1}></Col>
          <Col span={22}>
            <Image src={ImgId}></Image>
          </Col>
          <Col span={1}></Col>
        </Row>
      </Modal>
    </>
  );
};

export default ItemList;
